package com.hgxd.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgxd.entity.pojo.SysMenu;
import com.hgxd.entity.pojo.SysRole;
import com.hgxd.entity.pojo.SysUser;
import com.hgxd.entity.pojo.SysUserRole;
import com.hgxd.entity.res.ResOptions;
import com.hgxd.entity.res.ResUserVo;
import com.hgxd.entity.vo.pagevo.SysUserPageVo;
import com.hgxd.exception.ServiceException;
import com.hgxd.mapper.SysMenuMapper;
import com.hgxd.mapper.SysRoleMapper;
import com.hgxd.mapper.SysUserMapper;
import com.hgxd.mapper.SysUserRoleMapper;
import com.hgxd.result.ResultCodeEnum;
import com.hgxd.service.SysUserService;
import com.hgxd.utils.MenuUtils;
import com.hgxd.utils.security.JwtHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import java.util.*;

/**
 * @author wtf
 * @create 2023-07-24 17:06
 * @description :
 */
@Service("SysUserServiceImpl")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {


    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public Map<Integer, ResUserVo> getUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new ServiceException(ResultCodeEnum.DATA_ERROR, "没有携带token");
        }
        Long userId = JwtHelper.getUserId(token);
        List<ResUserVo> sysUser = sysUserMapper.selectRoleById(userId);
        Map<Integer, ResUserVo> objectObjectMap = new HashMap<>();
        for (int i = sysUser.size(); i > 0; i--) {
            String jsonString = JSON.toJSONString(sysUser.get(i - 1));
            objectObjectMap.put(i, JSON.parseObject(jsonString, ResUserVo.class));
        }
        // 获取特定用户的菜单记录列表 此sysMenuList是有菜单（一级菜单和二级菜单）有按钮的
        List<SysMenu> sysMenuList = sysMenuMapper.getSysMenuListByUserId(JwtHelper.getUserId(token));


        // 获取对应角色需要的菜单列表（树型）
        List<SysMenu> menuTreeList = getMenuList(sysMenuList);
        List<String> collect = menuTreeList.stream().map(SysMenu::getName).collect(Collectors.toList());
        ResUserVo resUserVo = new ResUserVo();
        resUserVo.setMenuListNoTree(collect);
//        resUserVo.setMenuList(menuTreeList);
        objectObjectMap.put(0, resUserVo);

        return objectObjectMap;
//        return JSON.parseObject(jsonString, ResUserVo.class);
//        return sysUser;
    }

    @Override
    public List<ResUserVo> findAllUsers() {
        List<SysUser> list = sysUserMapper.selectList(null);
        return sysUserToResUserVo(list);
    }


    @Override
    public Map<String, Object> selectUsersByPage(SysUserPageVo sysUserPageVo) {
        LambdaQueryWrapper<SysUser> sysUserQueryWrapper = new LambdaQueryWrapper<>();
        sysUserQueryWrapper.like(!"".equals(sysUserPageVo.getUsername()), SysUser::getUsername, sysUserPageVo.getUsername())
                .orderByDesc(SysUser::getUserId).eq(SysUser::getIsDeleted, "0");
        Page<SysUser> sysUserPage = sysUserMapper.selectPage(new Page<>(sysUserPageVo.getPageNum(), sysUserPageVo.getPageSize()), sysUserQueryWrapper);
        List<SysUser> list = sysUserPage.getRecords();
        List<ResUserVo> resUserVos = sysUserToResUserVo(list);
        long total = sysUserPage.getTotal();
        HashMap<String, Object> map = new HashMap<>();
        map.put("records", resUserVos);
        map.put("total", total);
        return map;
    }

    @Override
    public HashMap<String, List<ResOptions>> getApprover() {
        // 一级审批人信息
        List<ResOptions> firstApproverOptions = sysUserMapper.getUserOptionByRoleId(9L);
        // 二级审批人信息
        List<ResOptions> secondaryApproverOptions = sysUserMapper.getUserOptionByRoleId(12L);
        HashMap<String, List<ResOptions>> map = new HashMap<>();
        map.put("firstApproverOptions", firstApproverOptions);
        map.put("secondaryApproverOptions", secondaryApproverOptions);
        return map;
    }

    private List<ResUserVo> sysUserToResUserVo(List<SysUser> list) {
        ArrayList<ResUserVo> resUserVos = new ArrayList<>();
        for (SysUser sysUser : list) {
            List<String> roleNameByUserIds = sysRoleMapper.getRoleNameByUserId(sysUser.getUserId());
            HashMap<String, Object> map = new HashMap<>();
            map.put("roleName", roleNameByUserIds);
            String jsonString = JSON.toJSONString(sysUser);
            ResUserVo resUserVo = JSON.parseObject(jsonString, ResUserVo.class);
            resUserVo.setMap(map);
            resUserVos.add(resUserVo);
        }
        return resUserVos;

    }

    /**
     * 获取树形结构，以供前端动态路由
     *
     * @param sysMenuList
     * @return
     */
    private List<SysMenu> getMenuList(List<SysMenu> sysMenuList) {
        // 去重+去按钮
        List<SysMenu> allList = MenuUtils.removeRepeat(sysMenuList)
                .stream()
                .filter(menu -> menu.getType() != 2)
                .collect(Collectors.toList());

        //获取父id 即目录 然后根据sortValue进行排序
//        List<SysMenu> parentMenuList = allList.stream()
//                .filter(sysMenu -> sysMenu.getParentId() == 0)
//                .sorted(Comparator.comparing(SysMenu::getSortValue))
//                .collect(Collectors.toList());


//        return new SysMenuServiceImpl().setTree(allList,parentMenuList);
        return allList;
    }
}
